import { IApiRes, Profile } from "@/types/data";
import { getProfile, setProfile, removeProfile } from "@/utils/profile";
import request from "@/utils/request";
import { defineStore } from "pinia";

export default defineStore('user', {
    state() {
        return {
            profile: getProfile() as Profile
        }
    },
    actions: {
        async login(data:{account:string,password:string}) {
            const res = await request.post<IApiRes<Profile>>('/login', data)
            // console.log(res);
            // // this.profile = res.data.result 
            this.profile = res.data.result
            setProfile(res.data.result)
        },
        async sendCode(mobile:string) {
            const res = await request.get('/login/code', {
                params: {
                    mobile
                }
            })
        },
        async mobileLogin(mobile: string, code: string) {
            const res = await request.post<IApiRes<Profile>>('/login/code', {
                mobile,
                code
            })
            // 1. 保存用户信息到 state 中
            this.profile = res.data.result
            setProfile(res.data.result)
        },
        logout() {
            this.profile = {} as Profile
            removeProfile()
        },
        async loginQQ(id: string) {
            const res = await request.post<IApiRes<Profile>>('/login/social', {
                unionId: id,
                source: 6
            })
            this.profile = res.data.result
            setProfile(res.data.result)
        },
        // 绑定qq的短信验证码
        async sendQQBindMsg(mobile: string) {
            await request.get('/login/social/code', {
                params: {
                    mobile
                }
            })
        },
        async qqBindLogin(openId: string, mobile: string, code: string) {
            const res = await request.post<IApiRes<Profile>>('/login/social/bind', {
                mobile,
                code,
                unionId: openId
            })
            // 1. 保存用户信息到 state 中
            this.profile = res.data.result
            setProfile(res.data.result)
        },
    }
})